<template>
  <nav-bar>
    <div slot="left" class="left" @click="backHome">
      <van-icon name="arrow-left" />
    </div>
    <div slot="center">
      <van-search
        v-model="value"
        shape="round"
        background="#ff5456"
        placeholder="搜索你想要的区域"
        @search="onSearch"
      />
    </div>
    <div slot="right"></div>
  </nav-bar>
</template>

<script>
import NavBar from "@/components/common/navbar/NavBar";
import { mapMutations, mapState } from "vuex";
import { addHistorySearch } from "network/villagesearch";

export default {
  name: "",
  components: {
    NavBar,
  },
  data() {
    return {
      value: "",
    };
  },
  methods: {
    ...mapMutations({
      getvillageSearch: "moduleHotCity/getvillageSearch",
      addthistorySearch: "moduleHotCity/addthistorySearch",
    }),
    backHome() {
      this.$router.push("/");
    },
    serchHouse() {
      this.$router.push("/serchhouse");
    },
    //回车后可以确认输入,在这里可以跳转
    onSearch(val) {
      //这个val是我当前输入到框里的值

      //添加值到当前查询的地区的vuex中
      localStorage.setItem("villageSearch", val);
      this.getvillageSearch(val);

      //发送请求添加历史记录
      if (this.userId) {
        let userId = this.userId;
        let context = val;
        addHistorySearch({ userId, context }).then((res) => {
          this.$emit("onSearch", val);
        });
      }

      //添加历史搜索记录到vuex中
      this.addthistorySearch(val);

      //记录当前搜索小区的名字
      this.$router.push("/areasearch");
    },
  },
  activated() {
    document.getElementsByTagName("input")[0].focus();
  },
  deactivated() {
    this.value = "";
  },
  computed: {
    ...mapState({
      userId: (state) => state.moduleUser.userId,
    }),
  },
};
</script>

<style scoped>
.serch {
  height: 30px;
  width: 100%;
  border-radius: 20px;
  outline: none;
  border: 1px solid #ccc;
  text-indent: 15px;
  font-size: 13px;
}
.left {
  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.van-search {
  height: 30px;
}
</style>